package com.work.formaldehyde.activity;

import android.app.Activity;
import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.work.formaldehyde.R;
import com.work.formaldehyde.homefragment.WodeFragment;
import com.work.formaldehyde.model.JianCeDateModel;
import com.work.formaldehyde.model.WxModel;
import com.work.formaldehyde.util.ApiUtils;
import com.work.formaldehyde.util.PayResult;
import com.work.formaldehyde.util.Url;
import com.work.formaldehyde.wxapi.WXPayEntryActivity;

import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class QueRenDingDanActivity extends Activity implements View.OnClickListener {
    private ImageView comeback, gouwuche_img;
    private TextView title, shouhuodizhi, address_msg, phone, peisongdizhi, shangpingmingzi, gouwuche_manjian_text, gouwuche_money, yuyueshijian, yuyueshijians, gouwuche_numtext, yigong, allmoney;
    private RelativeLayout gouwuche_jiesuan, one, zhuangtai, gouwuche_jian, gouwuche_add;
    private EditText beizhu;
    private LinearLayout bottom_rela;
    private IWXAPI api;
    private String postmoney = "";
    private TextView shijitianshu;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApiUtils.ActivityIsLogin(this, 1);
        setContentView(R.layout.activity_querendingdan);
        api = WXAPIFactory.createWXAPI(this, Url.WXAPPID);
        comeback = findViewById(R.id.querendingdan_comeback);
        comeback.setOnClickListener(this);
        if (ApiUtils.isNetworkConnected(QueRenDingDanActivity.this))
            init();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private String addrname, addrphone, addresstrue, alljiage;
    private float getmoney, getmoneys;
    public static String phonestr = "", namestr = "", addrestr = "";
    public static String allmoneydingdan = "";
    private String suantianshu = "0";
    private int yuyuetianshu = 1;


    /**
     * 初始加载
     */
    public void init() {
        gouwuche_img = findViewById(R.id.gouwuche_img);
        gouwuche_jian = findViewById(R.id.gouwuche_jian);
        gouwuche_add = findViewById(R.id.gouwuche_add);
        gouwuche_jian.setOnClickListener(this);
        gouwuche_add.setOnClickListener(this);
        one = findViewById(R.id.one);
        zhuangtai = findViewById(R.id.zhuangtai);
        shouhuodizhi = findViewById(R.id.shouhuodizhi);
        shijitianshu = findViewById(R.id.shijitianshu);
        one.setOnClickListener(this);
        bottom_rela = findViewById(R.id.bottom_rela);
        Intent geti = getIntent();
        if (geti.getStringExtra("dingdan").equals("true")) {
            shangpingid = geti.getStringExtra("shangpingid");
            shangpingmoney = geti.getStringExtra("allmoney");
            postmoney = geti.getStringExtra("allmoney");
            suantianshu = geti.getStringExtra("suantianshu");
        } else {
            shangpingid = geti.getStringExtra("shangpingid");
            shangpingmoney = geti.getStringExtra("shangpingmoney");
            postmoney = geti.getStringExtra("shangpingmoney");
            suantianshu = geti.getStringExtra("suantianshu");
        }
        ApiUtils.GET_IMAGE(QueRenDingDanActivity.this, geti.getStringExtra("shangpingimg"), gouwuche_img);
        title = findViewById(R.id.title);
        address_msg = findViewById(R.id.address_msg);
        phone = findViewById(R.id.phone);
        peisongdizhi = findViewById(R.id.peisongdizhi);
        shangpingmingzi = findViewById(R.id.shangpingmingzi);
        gouwuche_manjian_text = findViewById(R.id.gouwuche_manjian_text);
        gouwuche_money = findViewById(R.id.gouwuche_money);
        gouwuche_money.setText("¥" + shangpingmoney + "元");
        yuyueshijian = findViewById(R.id.yuyueshijian);
        yuyueshijians = findViewById(R.id.yuyueshijians);
        gouwuche_numtext = findViewById(R.id.gouwuche_numtext);
        yigong = findViewById(R.id.yigong);
        allmoney = findViewById(R.id.allmoney);
        gouwuche_jiesuan = findViewById(R.id.gouwuche_jiesuan);
        gouwuche_jiesuan.setOnClickListener(this);
        beizhu = findViewById(R.id.beizhu);
        zfb = findViewById(R.id.zfb);
        zfb.setOnClickListener(this);
        DateTimePpicke(this);
        if (ShangPingActivity.ischeckaddress) {
            shouhuodizhi.setVisibility(View.GONE);
            title.setText(ShangPingActivity.addname);
            phone.setText(ShangPingActivity.addphone);
            address_msg.setText(ShangPingActivity.addresstrue);
            addrname = ShangPingActivity.addname;
            addrphone = ShangPingActivity.addphone;
            addresstrue = ShangPingActivity.addresstrue;
        } else {
            zhuangtai.setVisibility(View.GONE);
        }
        gouwuche_numtext.setText(indexs + "");
        allmoney.setText("¥" + shangpingmoney);

        getmoneys = Float.parseFloat(postmoney);
        getmoney = Float.parseFloat(postmoney);
        if (Url.MORENDIZHI != null) {
            zhuangtai.setVisibility(View.VISIBLE);
            shouhuodizhi.setVisibility(View.GONE);
            title.setText(Url.MORENNAME);
            phone.setText(Url.MORENPHONE);
            address_msg.setText(Url.MORENDIZHI);
            namestr = Url.MORENNAME;
            phonestr = Url.MORENPHONE;
            addrestr = Url.MORENDIZHI;
        }
    }

    public String times = "";
    public String shangpingid, shangpingmoney, shangpingshuliang;
    private LinearLayout zfb;
    String dangqiantime = "", jieshutime = "";

    private int indexs = 1;

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!phonestr.equals("") && !namestr.equals("") && !addrestr.equals("")) {
            zhuangtai.setVisibility(View.VISIBLE);
            shouhuodizhi.setText("");
            title.setText(namestr);
            phone.setText(phonestr);
            address_msg.setText(addrestr);
        }
        if (WXPayEntryActivity.wxclose) {
            WXPayEntryActivity.wxclose = false;
            onBackPressed();
        }
    }


    private String partnerId = "";

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.querendingdan_comeback:
                onBackPressed();
                break;
            case R.id.gouwuche_jiesuan:
                shangpingshuliang = gouwuche_numtext.getText().toString();
                if (dangqiantime.equals("")) {
                    ApiUtils.SetToast(QueRenDingDanActivity.this, "请选择开始时间");
                } else if (phonestr.equals("") || namestr.equals("") || addrestr.equals("")) {
                    ApiUtils.SetToast(QueRenDingDanActivity.this, "请选择收货地址");
                } else if (jieshutime.equals("")) {
                    ApiUtils.SetToast(QueRenDingDanActivity.this, "请选择结束时间");
                } else {
                    ApiUtils.windows(QueRenDingDanActivity.this, gouwuche_jiesuan, "生成订单中");
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            ApiUtils.closepopup();
                        }
                    }, 10000);
                    okHttp_postFromParameters();
                }
                break;
            case R.id.zfb:
                windows(this, 0);
                break;
            case R.id.gouwuche_jian:
                if (indexs > 1) {
                    getmoney = Float.parseFloat(shangpingmoney);
                    getmoneys = Float.parseFloat(shangpingmoney);
                    indexs--;
                    gouwuche_numtext.setText(indexs + "");
//                    gouwuche_money.setText("¥" + (getmoney * indexs) + "元");
                    allmoney.setText("¥" + ((Double.parseDouble(shangpingmoney) * moneynum) * indexs));
                    getmoney = Float.parseFloat(((Double.parseDouble(shangpingmoney) * moneynum) * indexs) + "");
                }
                break;
            case R.id.gouwuche_add:
                getmoney = Float.parseFloat(shangpingmoney);
                getmoneys = Float.parseFloat(shangpingmoney);
                ApiUtils.SetLog("indexs=" + indexs + ",getmoney=" + getmoneys);
                indexs++;
                gouwuche_numtext.setText(indexs + "");
//                gouwuche_money.setText("¥" + (getmoney * indexs) + "元");
                allmoney.setText("¥" + ((Double.parseDouble(shangpingmoney) * moneynum) * indexs));
                getmoney = Float.parseFloat(((Double.parseDouble(shangpingmoney) * moneynum) * indexs) + "");

                break;
            case R.id.one:
                Intent toaddress = new Intent(QueRenDingDanActivity.this, SelectAddressActivity.class);
                startActivity(toaddress, ActivityOptions.makeSceneTransitionAnimation(QueRenDingDanActivity.this).toBundle());
                break;
        }
    }

    private static PopupWindow popupWindows;

    public void windows(Context context, int sids) {
        View popupwindowviews = null;
        if (sids == 0) {
            popupwindowviews = LayoutInflater.from(context).inflate(
                    R.layout.popup_nowlite, null);
            RelativeLayout dangqian = popupwindowviews.findViewById(R.id.dangqian);
            dangqian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    yuyueshijian.setText("");
                    jieshutime = "";
                    dangqiantime = "";
                    sid = 0;
                    pvTime.show();
                    popupWindows.dismiss();
                }
            });
            RelativeLayout jieshu = popupwindowviews.findViewById(R.id.jieshu);
            jieshu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sid = 1;
                    pvTime.show();
                    popupWindows.dismiss();
                }
            });
        } else {
            popupwindowviews = LayoutInflater.from(context).inflate(
                    R.layout.popup_zfbandwx, null);
            RelativeLayout zfb = popupwindowviews.findViewById(R.id.zfb);
            zfb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ApiUtils.windows(QueRenDingDanActivity.this, gouwuche_jiesuan, "发起支付");
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            ApiUtils.closepopup();
                        }
                    }, 10000);
                    getalipay();
                    popupWindows.dismiss();
                }
            });
            RelativeLayout wx = popupwindowviews.findViewById(R.id.wx);
            wx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ApiUtils.windows(QueRenDingDanActivity.this, gouwuche_jiesuan, "发起支付");
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
                            ApiUtils.closepopup();
                        }
                    }, 10000);
                    okHttp_postFromParameters1();
                    popupWindows.dismiss();
                }
            });
        }
        popupWindows = new PopupWindow(popupwindowviews, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        popupWindows.setAnimationStyle(R.style.popwin_anim_style);
        popupWindows.setTouchable(true);
        popupWindows.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // TODO Auto-generated method stub
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        popupWindows.setFocusable(true);
        popupWindows.setOutsideTouchable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.4f;
        getWindow().setAttributes(lp);
        popupWindows.showAtLocation(bottom_rela, Gravity.BOTTOM, 0, 0);
    }


    private void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("goods_id", shangpingid).add("goods_num", shangpingshuliang).add("order_money", getmoney + "").add("user_name", title.getText().toString()).add("user_address", address_msg.getText().toString()).add("user_phone", phone.getText().toString()).add("remarks", beizhu.getText().toString()).add("start_time", dangqiantime).add("end_time", jieshutime)
                            .build();
                    ApiUtils.SetLog("user_address" + address_msg.getText().toString());
                    Request request = new Request.Builder().url(Url.CREDINGDAN).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot1.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    private void okHttp_postFromParameters1() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
//                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("ordernum", orderNum).add("goods_num", shangpingshuliang).add("order_money", postmoney + "").add("user_name", title.getText().toString()).add("user_address", address_msg.getText().toString()).add("user_phone", phone.getText().toString()).add("remarks", beizhu.getText().toString()).add("start_time", dangqiantime).add("end_time", jieshutime)
//                            .build();
                    RequestBody formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("ordernum", orderNum)
                            .build();
//                    Request request = new Request.Builder().url(Url.GETWXPALY).post(formBody).build();
                    Request request = new Request.Builder().url(Url.WXPAY).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethots.sendMessage(message);
//                    Request request = new Request.Builder().get().url(Url.WXPAY + Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN + "&ordernum=" + orderNum).build();
//                    Call call = okHttpClient.newCall(request);
//                    call.enqueue(new Callback() {
//                        @Override
//                        public void onFailure(Call call, IOException e) {
//                        }
//
//                        @Override
//                        public void onResponse(Call call, final Response response) {
//                            try {
//                                final String responseStr;
//                                responseStr = response.body().string();
//                                Message message = new Message();
//                                message.obj = responseStr;
//                                gethots.sendMessage(message);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    private String orderNum, nonceStr = "";
    public Handler gethot1 = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        String data = success_Object.getString("data");
                        success_Object = new JSONObject(data);
                        orderNum = success_Object.getString("orderNum");
                        Url.PAY_OREDNUM = orderNum;
                        windows(QueRenDingDanActivity.this, 1);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    WxModel wxModel;
    public Handler gethots = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        wxModel = gson.fromJson(msg.obj.toString(),
                                WxModel.class);
                        partnerId = wxModel.getData().getPrepay_id();
                        nonceStr = wxModel.getData().getNoncestr();
                        try {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date date = new Date(System.currentTimeMillis());
                            times = ApiUtils.dateToStamp(simpleDateFormat.format(date));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        Url.wxdingdan = true;
                        PayReq request = new PayReq();
                        request.appId = Url.WXAPPID;
                        request.partnerId = Url.WXSHNUM;
                        request.prepayId = partnerId;
                        request.packageValue = "Sign=WXPay";
                        request.nonceStr = nonceStr;
                        request.timeStamp = wxModel.getData().getTimestamp();
                        request.sign = wxModel.getData().getRequest_sign();
                        api.sendReq(request);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void getalipay() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = null;
                    formBody = new FormBody.Builder().add("uid", Url.USER_ID).add("logintoken", Url.LOGIN_TOKEN).add("ordernum", orderNum)
                            .build();
                    Url.PAY_OREDNUM = orderNum;
//                    Request request = new Request.Builder().url(Url.GETALIPALY).post(formBody).build();
                    Request request = new Request.Builder().url(Url.ALIPAY).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    getalihots.sendMessage(message);
//                    Request request = new Request.Builder().get().url(Url.ALIPAY + Url.USER_ID + "&logintoken=" + Url.LOGIN_TOKEN + "&ordernum=" + orderNum).build();
//                    Call call = okHttpClient.newCall(request);
//                    call.enqueue(new Callback() {
//                        @Override
//                        public void onFailure(Call call, IOException e) {
//                        }
//
//                        @Override
//                        public void onResponse(Call call, final Response response) {
//                            try {
//                                final String responseStr;
//                                responseStr = response.body().string();
//                                Message message = new Message();
//                                message.obj = responseStr;
//                                getalihots.sendMessage(message);
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    });
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public String alipay_str;

    public Handler getalihots = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    ApiUtils.closepopup();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        alipay_str = success_Object.getString("data");
                        Thread payThread = new Thread(payRunnable);
                        payThread.start();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    Runnable payRunnable = new Runnable() {
        private static final int SDK_PAY_FLAG = 1;

        @Override
        public void run() {
            PayTask alipay = new PayTask(QueRenDingDanActivity.this);
            Map<String, String> result = alipay.payV2(alipay_str, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            if (TextUtils.equals(resultStatus, "9000")) {
                onBackPressed();
                ApiUtils.SetToast(QueRenDingDanActivity.this, "支付成功");
                intent_to_orderactivity(1);
//                getalipays();
            } else {
                intent_to_orderactivity(0);
                onBackPressed();
                ApiUtils.SetToast(QueRenDingDanActivity.this, "支付失败");
            }
//            try {
//                JSONObject success_Object = new JSONObject(msg.obj.toString());
//                String code = success_Object.getString("msg");
//                ApiUtils.SetLog("支付=" + code);
//                if (code.equals("Success")) {
//                    ApiUtils.SetLog("支付结果:成功");
//                    getalipays();
//                } else {
//                    ApiUtils.SetLog("支付失败");
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }

        }
    };

    private void getalipays() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = null;
                    formBody = new FormBody.Builder().add("paytype", "支付宝支付").add("order_number", Url.PAY_OREDNUM)
                            .build();
                    Request request = new Request.Builder().url(Url.PAYCSECSS).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    getalihotss.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).
                start();
    }

    public Handler getalihotss = new Handler() {
        public void handleMessage(Message msg) {
            JSONObject success_Object;
            try {
                if (msg.obj != null) {
                    onBackPressed();
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    if (code.equals("1")) {
                        intent_to_orderactivity(1);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public void intent_to_orderactivity(int id) {
        WodeFragment.sid = id;
        Intent order = new Intent(QueRenDingDanActivity.this, OrderActivity.class);
        startActivity(order, ActivityOptions.makeSceneTransitionAnimation(QueRenDingDanActivity.this).toBundle());
        Url.wxdingdan = false;
        Url.wxgwc = false;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ApiUtils.popupWindows != null && ApiUtils.popupWindows.isShowing()) {
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    TimePickerView pvTime;
    int sid = 0;
    String huoqujieshu;
    public boolean tanchu = false;

    public void DateTimePpicke(Context context) {
        Calendar selectedDate = Calendar.getInstance();
        Time t = new Time();
        t.setToNow(); // 取得系统时间。
        int year = t.year;
        int month = t.month;
        int day = t.monthDay;
        int mWay = selectedDate.get(Calendar.DAY_OF_WEEK);
//        String mway = null;
//        mway = Apiutils.GetWeekday(mWay);
        int h = t.hour;
        int m = t.minute;
//        bwl_tiem.setText(year + "年" + (month + 1) + "月" + day + "日" + " 周" + mway + " " + h + ":" + m);
        selectedDate.set(year, month, day);
        pvTime = new TimePickerBuilder(context, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                int mway = calendar.get(Calendar.DAY_OF_WEEK);
                int h = calendar.get(Calendar.HOUR_OF_DAY);
                huoqujieshu = year + "-" + month + "-" + day;
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date datetime = new Date(System.currentTimeMillis());
                if (ApiUtils.dateDiff(simpleDateFormat.format(datetime), huoqujieshu) < 5) {
                    ApiUtils.SetToast(QueRenDingDanActivity.this, "当前预约已满，请选择其他时间");
                    tanchu = true;
                } else {
                    if (sid == 0) {
                        tanchu = false;
                        dangqiantime = year + "-" + month + "-" + day;
                        if (dangqiantime.equals(""))
                            yuyueshijian.setText(dangqiantime);
                        if (!dangqiantime.equals("") && jieshutime.equals(""))
                            yuyueshijian.setText(dangqiantime + "~" + jieshutime);
                        if (!dangqiantime.equals("") && !jieshutime.equals(""))
                            yuyueshijian.setText(dangqiantime + "~" + jieshutime);
                        yuyueshijians.setVisibility(View.GONE);
                        yuyueshijian.setVisibility(View.VISIBLE);
                        sid = 1;
                        pvTime.show();
                    }
                }
                if (sid == 1 && !dangqiantime.equals(year + "-" + month + "-" + day) && ApiUtils.dateDiff(dangqiantime, huoqujieshu) > 0) {
                    jieshutime = year + "-" + month + "-" + day;
                    sid = 2;
                    if (jieshutime.equals("") && dangqiantime.equals(""))
                        yuyueshijian.setText(jieshutime);
                    if (!dangqiantime.equals("") && jieshutime.equals(""))
                        yuyueshijian.setText(jieshutime);
                    if (!dangqiantime.equals("") && !jieshutime.equals(""))
                        yuyueshijian.setText(dangqiantime + "~" + jieshutime);

                    yuyueshijians.setVisibility(View.GONE);
                    yuyueshijian.setVisibility(View.VISIBLE);
                    if (suantianshu.equals("1")) {
                        yuyuetianshu = (int) ApiUtils.dateDiff(dangqiantime, jieshutime);
                        moneynum = Double.parseDouble(yuyuetianshu + "");
                        double moneys = (Double.parseDouble(shangpingmoney) * moneynum) * indexs;
                        allmoney.setText("¥" + moneys);
                        postmoney = moneys + "";
                        getmoney = Float.parseFloat(postmoney);
                        shijitianshu.setText("实际使用天数:" + yuyuetianshu);
                    } else {
                        yuyuetianshu = (int) ApiUtils.dateDiff(dangqiantime, jieshutime);
                        shijitianshu.setText("实际使用天数:" + yuyuetianshu);
                    }
                }
            }
//                bwl_tiem.setText(year + "年" + month + "月" + day + "日" + " 周" + Apiutils.GetWeekday(mway) + " " + h + ":" + calendar.get(Calendar.MINUTE));
//                gettimestr = year + "年" + month + "月" + day + "日" + " " + h + ":" + calendar.get(Calendar.MINUTE);
        }).setDate(selectedDate)
                .setSubmitColor(R.color.text_black40)
                .setCancelColor(R.color.text_black40)
                .setOutSideCancelable(false)
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .build();
        pvTime.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {
                if (sid == 1 && jieshutime.equals("")) {
                    ApiUtils.SetToast(QueRenDingDanActivity.this, "请选择结束时间");
                    pvTime.show();
                }
                if (tanchu) {
                    pvTime.show();
                }
            }
        });
    }

    double moneynum = 1;

}
